<?php
/**
 * 数据导出助手类
 */
class Excel {
    public $lists;
    public $columns;
    public $fileName;
    public $enclosure;
    public function __construct($info) {
        $this->lists = $info['lists'];
        $this->columns = $info['columns'];
        $this->fileName = $info['fileName'];
        $this->enclosure = $info['enclosure'] ?? null;
    }
    public function run(){
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename={$this->fileName}.xls");
        $str = '';
        $str .= '<table><tr>';
        $columns = array_values($this->columns);
        for($i=0;$i<count($columns);$i++){
            $name = gettype($columns[$i]) == 'array' ? $columns[$i]['attr'] : $columns[$i];
            $str .= "<th>{$name}</th>";
        }
        $str .= '</tr>';
        foreach ($this->lists as $key=>$row) {
            $str .= '<tr>';
            foreach ($this->columns as $key => $value) {
                $td = '';
                $td .= '<td>';
                if(gettype($value) == 'array'){
                    $td .= call_user_func($value['value'], $row, $this->enclosure);
                } else {
                    $td .= $row[$key];
                }
                $td .= '</td>';
                $str .= $td;
            }
            $str .= '</tr>';
        }
        $str .= '</table>';
        echo $str;
        die;
    }
}